package com.ideaplugin.datamanager.config;

import cn.hutool.core.util.IdUtil;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created on 2022/7/19.
 *
 * @author zhaojb
 */
@WebFilter("/**")
@Configuration
public class MdcFilter implements Filter {
    public static final String requestId = "requestId";
    public static final String requestURI = "requestURI";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        MDC.put(requestId, IdUtil.fastSimpleUUID());
        MDC.put(requestURI, ((HttpServletRequest) request).getRequestURI());
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {
        MDC.clear();
    }
}
